
/*****************************************************************************\
 *            Extract average time for a range of distances
 * Usage: avg_dist <filename> <mindist> <maxdist>
 *
 * gcc -ansi avg_dist.c -o avg_dist
\*****************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>


int main( int argc, char *argv[] )
{
	FILE *datafile;
	#define	linesize 1000
	char line[linesize];
	float dist, time, sum;
	float mindist, maxdist;
	int ndist;


	if ( argc < 4 )
	{
		fputs("avg_dist: not enough args!\n", stderr );
		exit(-1);
	}

	mindist = atof( argv[2] );
	maxdist = atof( argv[3] );

	datafile = fopen( argv[1], "r" );
	if ( ! datafile )
	{
		perror("fopen");
		fprintf(stderr," filename = %s .\n", argv[1] );
		exit(-1);
	}

	sum = 0.0;
	ndist = 0;

	while ( fgets(line, linesize, datafile) )
	{
		if ( ! strcmp(line,"0 0\n") )
		{
			// was generated by some script because data file was missing
			putchar('\n');
			fclose( datafile );
			exit(0);
		}

		if ( ! isdigit(line[0]) && line[0] != '.' )
			continue;

		sscanf( line, "%f %f", &dist, &time );

		if ( dist <= maxdist && dist >= mindist )
		{
			sum += time;
			ndist ++ ;
		}
	}

	if ( ndist )
		printf("%f\n", sum / ndist );
	else
		fputs("avg_dist: no samples inside distance range!\n", stderr );

	fclose( datafile );
}


